{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "986dcf71",
   "metadata": {},
   "outputs": [],
   "source": [
    "import backtrader as bt\n",
    "import os\n",
    "import sys\n",
    "import datetime\n",
    "from backtrader.indicators import EMA"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "35fca67a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "启动资金: 2000000.00\n",
      "2020-02-06, 买入, 7452.25\n",
      "2020-02-24, 卖出, 7910.12\n",
      "2020-02-25, 交易中，毛利34054.80, 净利 26455.48\n",
      "2020-03-03, 买入, 7778.03\n",
      "2020-03-09, 卖出, 7748.18\n",
      "2020-03-10, 交易中，毛利-6217.81, 净利 -13942.85\n",
      "2020-03-20, 买入, 6897.38\n",
      "2020-03-23, 卖出, 6677.63\n",
      "2020-03-24, 交易中，毛利13764.52, 净利 7012.88\n",
      "2020-03-24, 买入, 6949.99\n",
      "2020-04-10, 卖出, 7698.10\n",
      "2020-04-13, 交易中，毛利46583.77, 净利 39168.78\n",
      "2020-04-14, 买入, 7796.45\n",
      "2020-04-15, 卖出, 7781.48\n",
      "2020-04-16, 交易中，毛利-7686.88, 净利 -15470.20\n",
      "2020-04-20, 买入, 7858.66\n",
      "2020-04-21, 卖出, 7669.13\n",
      "2020-04-22, 交易中，毛利-15218.81, 净利 -22961.68\n",
      "2020-04-22, 买入, 7898.31\n",
      "2020-04-23, 卖出, 7917.97\n",
      "2020-04-24, 交易中，毛利4574.14, 净利 -3372.47\n",
      "2020-04-24, 买入, 8007.13\n",
      "2020-04-27, 卖出, 7944.40\n",
      "2020-04-28, 交易中，毛利2850.35, 净利 -5134.75\n",
      "2020-04-28, 买入, 8181.22\n",
      "2020-04-29, 卖出, 8074.56\n",
      "2020-04-30, 交易中，毛利-10470.14, 净利 -18599.26\n",
      "2020-05-06, 买入, 8162.35\n",
      "2020-05-11, 卖出, 8375.89\n",
      "2020-05-12, 交易中，毛利18711.53, 净利 10452.86\n",
      "2020-05-12, 买入, 8404.91\n",
      "2020-05-15, 卖出, 8504.83\n",
      "2020-05-18, 交易中，毛利8684.73, 净利 238.56\n",
      "2020-05-18, 买入, 8765.27\n",
      "2020-05-20, 卖出, 8761.62\n",
      "2020-05-21, 交易中，毛利-5175.47, 净利 -13993.85\n",
      "2020-05-26, 买入, 8789.43\n",
      "2020-05-27, 卖出, 8708.45\n",
      "2020-05-28, 交易中，毛利-8173.82, 净利 -16925.77\n",
      "2020-05-28, 买入, 8779.52\n",
      "2020-06-03, 卖出, 9039.73\n",
      "2020-06-04, 交易中，毛利31182.41, 净利 22276.40\n",
      "2020-06-04, 买入, 9226.73\n",
      "2020-06-11, 卖出, 9409.03\n",
      "2020-06-12, 交易中，毛利1108.68, 净利 -8130.07\n",
      "2020-06-19, 买入, 9499.96\n",
      "2020-07-03, 卖出, 10699.51\n",
      "2020-07-06, 交易中，毛利115049.56, 净利 104976.41\n",
      "2020-07-06, 买入, 10980.42\n",
      "2020-07-07, 卖出, 11338.28\n",
      "2020-07-08, 交易中，毛利30793.63, 净利 19700.72\n",
      "2020-07-09, 买入, 11510.74\n",
      "2020-07-10, 卖出, 11668.21\n",
      "2020-07-13, 交易中，毛利18089.01, 净利 6555.97\n",
      "2020-07-13, 买入, 12224.95\n",
      "2020-07-16, 卖出, 11346.03\n",
      "2020-07-17, 交易中，毛利-119891.81, 净利 -131528.23\n",
      "2020-07-23, 买入, 11657.29\n",
      "2020-07-24, 卖出, 11096.38\n",
      "2020-07-27, 交易中，毛利-41996.03, 净利 -53354.68\n",
      "2020-07-28, 买入, 11544.19\n",
      "2020-08-06, 卖出, 11351.57\n",
      "2020-08-07, 交易中，毛利-23566.02, 净利 -35032.24\n",
      "2020-08-14, 买入, 11616.33\n",
      "2020-08-20, 卖出, 11714.31\n",
      "2020-08-21, 交易中，毛利12047.60, 净利 296.65\n",
      "2020-08-24, 买入, 12119.10\n",
      "2020-08-31, 卖出, 13351.64\n",
      "2020-09-01, 交易中，毛利111046.14, 净利 98337.28\n",
      "2020-09-11, 买入, 12768.11\n",
      "2020-09-17, 卖出, 12316.39\n",
      "2020-09-18, 交易中，毛利-55826.64, 净利 -68388.08\n",
      "2020-09-18, 买入, 12493.84\n",
      "2020-09-21, 卖出, 12293.61\n",
      "2020-09-22, 交易中，毛利-32114.42, 净利 -44430.96\n",
      "2020-09-28, 买入, 12028.66\n",
      "2020-10-16, 卖出, 12978.43\n",
      "2020-10-19, 交易中，毛利95384.07, 净利 82794.15\n",
      "2020-10-20, 买入, 13305.61\n",
      "2020-10-23, 卖出, 13254.59\n",
      "2020-10-26, 交易中，毛利-44846.71, 净利 -57916.80\n",
      "2020-10-28, 买入, 13688.22\n",
      "2020-10-30, 卖出, 13671.59\n",
      "2020-11-02, 交易中，毛利1445.36, 净利 -12246.21\n",
      "2020-11-02, 买入, 13920.55\n",
      "2020-11-11, 卖出, 15002.96\n",
      "2020-11-12, 交易中，毛利93105.86, 净利 78678.57\n",
      "2020-11-12, 买入, 15287.41\n",
      "2020-11-13, 卖出, 14723.82\n",
      "2020-11-16, 交易中，毛利-31017.34, 净利 -45917.00\n",
      "2020-11-16, 买入, 15366.53\n",
      "2020-11-17, 卖出, 15143.25\n",
      "2020-11-18, 交易中，毛利-25619.33, 净利 -40819.08\n",
      "2020-11-23, 买入, 15351.51\n",
      "2020-11-25, 卖出, 14867.70\n",
      "2020-11-26, 交易中，毛利-50750.22, 净利 -65789.99\n",
      "2020-12-03, 买入, 14846.94\n",
      "2020-12-18, 卖出, 17067.04\n",
      "2020-12-21, 交易中，毛利213651.21, 净利 197752.73\n",
      "2020-12-22, 买入, 17502.80\n",
      "2020-12-23, 卖出, 17390.93\n",
      "2020-12-24, 交易中，毛利-49985.81, 净利 -67287.69\n",
      "2020-12-28, 买入, 17909.46\n",
      "2021-01-06, 卖出, 20220.63\n",
      "2021-01-07, 交易中，毛利219884.48, 净利 200833.04\n",
      "2021-01-07, 买入, 20530.71\n",
      "2021-01-08, 卖出, 19865.32\n",
      "2021-01-11, 交易中，毛利-80147.10, 净利 -100263.89\n",
      "2021-01-21, 买入, 18228.48\n",
      "2021-01-28, 卖出, 18014.61\n",
      "2021-01-29, 交易中，毛利1413.03, 净利 -16793.41\n",
      "2021-01-29, 买入, 18368.16\n",
      "2021-02-18, 卖出, 20252.53\n",
      "2021-02-19, 交易中，毛利170621.09, 净利 151367.34\n",
      "2021-03-03, 买入, 16672.44\n",
      "2021-03-04, 卖出, 15797.40\n",
      "2021-03-05, 交易中，毛利-88826.86, 净利 -104736.17\n",
      "2021-03-05, 买入, 15994.77\n",
      "2021-03-08, 卖出, 14799.18\n",
      "2021-03-09, 交易中，毛利-143653.38, 净利 -159009.48\n",
      "2021-03-10, 买入, 14834.67\n",
      "2021-03-25, 卖出, 15479.75\n",
      "2021-03-26, 交易中，毛利71220.84, 净利 56000.27\n",
      "2021-03-26, 买入, 16078.08\n",
      "2021-03-31, 卖出, 16149.39\n",
      "2021-04-01, 交易中，毛利-951.53, 净利 -17186.65\n",
      "2021-04-01, 买入, 16567.68\n",
      "2021-04-07, 卖出, 16344.57\n",
      "2021-04-08, 交易中，毛利-78349.05, 净利 -94844.80\n",
      "2021-04-16, 买入, 16879.95\n",
      "2021-04-26, 卖出, 17684.46\n",
      "2021-04-27, 交易中，毛利99312.27, 净利 82010.79\n",
      "2021-04-27, 买入, 17942.38\n",
      "2021-04-30, 卖出, 18171.81\n",
      "2021-05-06, 交易中，毛利33846.03, 净利 16027.70\n",
      "2021-05-12, 买入, 17916.98\n",
      "2021-05-26, 卖出, 20065.08\n",
      "2021-05-27, 交易中，毛利234167.84, 净利 215313.21\n",
      "2021-06-01, 买入, 20592.09\n",
      "2021-06-02, 卖出, 20277.03\n",
      "2021-06-03, 交易中，毛利-30393.75, 净利 -50782.38\n",
      "2021-06-04, 买入, 21025.45\n",
      "2021-06-08, 卖出, 19905.75\n",
      "2021-06-09, 交易中，毛利-147261.06, 净利 -167621.21\n",
      "2021-06-22, 买入, 19344.57\n",
      "2021-06-23, 卖出, 18638.90\n",
      "2021-06-24, 交易中，毛利-74491.21, 净利 -93439.39\n",
      "2021-06-24, 买入, 18803.64\n",
      "2021-06-25, 订单取消或被拒绝\n",
      "2021-07-07, 买入, 18952.72\n",
      "2021-07-08, 订单取消或被拒绝\n",
      "2021-07-13, 买入, 18554.44\n",
      "2021-07-22, 卖出, 18791.56\n",
      "2021-07-23, 交易中，毛利27529.28, 净利 8983.25\n",
      "2021-08-02, 买入, 15984.87\n",
      "2021-08-16, 卖出, 16420.51\n",
      "2021-08-17, 交易中，毛利67050.13, 净利 50993.29\n",
      "2021-08-24, 买入, 15135.08\n",
      "2021-09-09, 卖出, 15579.36\n",
      "2021-09-10, 交易中，毛利29610.82, 净利 14167.31\n",
      "2021-09-10, 买入, 15962.16\n",
      "2021-09-14, 卖出, 15766.36\n",
      "2021-09-15, 交易中，毛利-22827.54, 净利 -38599.89\n",
      "2021-09-17, 买入, 16107.23\n",
      "2021-09-22, 卖出, 15566.45\n",
      "2021-09-23, 交易中，毛利-24734.63, 净利 -40445.76\n",
      "2021-09-24, 买入, 16064.81\n",
      "2021-10-15, 卖出, 17962.58\n",
      "2021-10-18, 交易中，毛利109147.07, 净利 92130.33\n",
      "2021-10-22, 买入, 17485.34\n",
      "2021-10-25, 卖出, 17278.54\n",
      "2021-10-26, 交易中，毛利-15259.92, 净利 -32562.60\n",
      "2021-10-29, 买入, 16981.25\n",
      "2021-11-02, 卖出, 16482.50\n",
      "2021-11-03, 交易中，毛利-6636.45, 净利 -23185.68\n",
      "2021-11-04, 买入, 17000.33\n",
      "2021-11-10, 卖出, 16545.88\n",
      "2021-11-11, 交易中，毛利-44739.19, 净利 -61483.02\n",
      "2021-11-16, 买入, 16981.86\n",
      "2021-11-26, 卖出, 17619.73\n",
      "2021-11-29, 交易中，毛利60980.34, 净利 43783.38\n",
      "2021-11-29, 买入, 17754.94\n",
      "2021-11-30, 卖出, 17389.39\n",
      "2021-12-01, 交易中，毛利-19451.83, 净利 -37155.36\n",
      "2021-12-03, 买入, 18239.10\n",
      "2021-12-07, 卖出, 18096.85\n",
      "2021-12-08, 交易中，毛利-21321.42, 净利 -39504.83\n",
      "2021-12-08, 买入, 18826.61\n",
      "2021-12-09, 订单取消或被拒绝\n",
      "2021-12-23, 买入, 18642.78\n",
      "2021-12-24, 订单取消或被拒绝\n",
      "2022-01-10, 买入, 16910.52\n",
      "2022-01-11, 卖出, 16715.71\n",
      "2022-01-12, 交易中，毛利-13527.75, 净利 -30339.27\n",
      "2022-01-12, 买入, 16806.56\n",
      "2022-01-13, 卖出, 16217.47\n",
      "2022-01-14, 交易中，毛利-66576.59, 净利 -83064.44\n",
      "2022-01-17, 买入, 16189.26\n",
      "2022-01-25, 卖出, 16274.77\n",
      "2022-01-26, 交易中，毛利6404.19, 净利 -9818.59\n",
      "2022-02-09, 买入, 16021.48\n",
      "2022-02-22, 卖出, 16238.06\n",
      "2022-02-23, 交易中，毛利29080.96, 净利 12947.15\n",
      "2022-03-01, 买入, 16397.26\n",
      "2022-03-03, 卖出, 15666.03\n",
      "2022-03-04, 交易中，毛利-74005.77, 净利 -89865.29\n",
      "2022-03-09, 买入, 14864.07\n",
      "2022-03-14, 卖出, 14564.72\n",
      "2022-03-15, 交易中，毛利-119760.94, 净利 -134514.18\n",
      "2022-03-16, 买入, 14244.50\n",
      "2022-03-25, 卖出, 13874.83\n",
      "2022-03-28, 交易中，毛利-99501.55, 净利 -113512.92\n",
      "2022-03-30, 买入, 13842.95\n",
      "2022-03-31, 订单取消或被拒绝\n",
      "2022-04-12, 买入, 14052.18\n",
      "2022-04-13, 订单取消或被拒绝\n",
      "2022-04-27, 买入, 14244.28\n",
      "2022-04-28, 订单取消或被拒绝\n",
      "2022-05-12, 买入, 14456.83\n",
      "2022-05-13, 订单取消或被拒绝\n",
      "2022-05-30, 买入, 14751.70\n",
      "2022-05-31, 订单取消或被拒绝\n",
      "2022-06-15, 买入, 15804.36\n",
      "2022-06-16, 订单取消或被拒绝\n",
      "2022-06-24, 买入, 16539.69\n",
      "2022-06-27, 订单取消或被拒绝\n",
      "2022-06-30, 买入, 17449.77\n",
      "2022-07-01, 订单取消或被拒绝\n",
      "2022-07-18, 买入, 16055.42\n",
      "2022-07-19, 订单取消或被拒绝\n",
      "2022-08-04, 买入, 15633.95\n",
      "2022-08-05, 订单取消或被拒绝\n",
      "2022-08-11, 买入, 15627.53\n",
      "2022-08-12, 订单取消或被拒绝\n",
      "2022-08-17, 买入, 15687.68\n",
      "2022-08-18, 订单取消或被拒绝\n",
      "2022-08-25, 买入, 15479.61\n",
      "2022-08-26, 订单取消或被拒绝\n",
      "2022-08-31, 买入, 15673.36\n",
      "2022-09-01, 订单取消或被拒绝\n",
      "2022-09-09, 买入, 14932.62\n",
      "2022-09-13, 订单取消或被拒绝\n",
      "2022-09-19, 买入, 14876.90\n",
      "2022-09-20, 订单取消或被拒绝\n",
      "2022-09-26, 买入, 15024.92\n",
      "2022-09-27, 订单取消或被拒绝\n",
      "2022-10-20, 买入, 13804.92\n",
      "2022-10-21, 订单取消或被拒绝\n",
      "2022-10-31, 买入, 11848.75\n",
      "2022-11-14, 卖出, 13465.00\n",
      "2022-11-15, 交易中，毛利147732.89, 净利 135026.24\n",
      "2022-11-15, 买入, 13806.57\n",
      "2022-11-17, 卖出, 13671.79\n",
      "2022-11-18, 交易中，毛利-2270.08, 净利 -15990.56\n",
      "2022-11-28, 买入, 13125.16\n",
      "2022-12-12, 卖出, 15265.93\n",
      "2022-12-13, 交易中，毛利187228.29, 净利 172914.02\n",
      "2022-12-14, 买入, 15942.44\n",
      "2022-12-15, 卖出, 15787.42\n",
      "2022-12-16, 交易中，毛利-36676.60, 净利 -52528.38\n",
      "2022-12-23, 买入, 15715.63\n",
      "2022-12-26, 卖出, 15502.05\n",
      "2022-12-27, 交易中，毛利-10590.24, 净利 -26249.88\n",
      "2022-12-27, 买入, 15724.80\n",
      "2022-12-28, 订单取消或被拒绝\n",
      "2022-12-30, 买入, 15609.71\n",
      "2023-01-03, 卖出, 15328.03\n",
      "2023-01-04, 交易中，毛利-29594.70, 净利 -45043.46\n",
      "2023-01-05, 买入, 16164.25\n",
      "2023-01-06, 订单取消或被拒绝\n",
      "2023-01-13, 买入, 17053.94\n",
      "2023-01-16, 订单取消或被拒绝\n",
      "2023-02-09, 买入, 16816.48\n",
      "2023-02-10, 订单取消或被拒绝\n",
      "2023-02-10, 最终的账户资产为1527411.43\n"
     ]
    },
    {
     "data": {
      "application/javascript": [
       "/* Put everything inside the global mpl namespace */\n",
       "window.mpl = {};\n",
       "\n",
       "\n",
       "mpl.get_websocket_type = function() {\n",
       "    if (typeof(WebSocket) !== 'undefined') {\n",
       "        return WebSocket;\n",
       "    } else if (typeof(MozWebSocket) !== 'undefined') {\n",
       "        return MozWebSocket;\n",
       "    } else {\n",
       "        alert('Your browser does not have WebSocket support. ' +\n",
       "              'Please try Chrome, Safari or Firefox ≥ 6. ' +\n",
       "              'Firefox 4 and 5 are also supported but you ' +\n",
       "              'have to enable WebSockets in about:config.');\n",
       "    };\n",
       "}\n",
       "\n",
       "mpl.figure = function(figure_id, websocket, ondownload, parent_element) {\n",
       "    this.id = figure_id;\n",
       "\n",
       "    this.ws = websocket;\n",
       "\n",
       "    this.supports_binary = (this.ws.binaryType != undefined);\n",
       "\n",
       "    if (!this.supports_binary) {\n",
       "        var warnings = document.getElementById(\"mpl-warnings\");\n",
       "        if (warnings) {\n",
       "            warnings.style.display = 'block';\n",
       "            warnings.textContent = (\n",
       "                \"This browser does not support binary websocket messages. \" +\n",
       "                    \"Performance may be slow.\");\n",
       "        }\n",
       "    }\n",
       "\n",
       "    this.imageObj = new Image();\n",
       "\n",
       "    this.context = undefined;\n",
       "    this.message = undefined;\n",
       "    this.canvas = undefined;\n",
       "    this.rubberband_canvas = undefined;\n",
       "    this.rubberband_context = undefined;\n",
       "    this.format_dropdown = undefined;\n",
       "\n",
       "    this.image_mode = 'full';\n",
       "\n",
       "    this.root = $('<div/>');\n",
       "    this._root_extra_style(this.root)\n",
       "    this.root.attr('style', 'display: inline-block');\n",
       "\n",
       "    $(parent_element).append(this.root);\n",
       "\n",
       "    this._init_header(this);\n",
       "    this._init_canvas(this);\n",
       "    this._init_toolbar(this);\n",
       "\n",
       "    var fig = this;\n",
       "\n",
       "    this.waiting = false;\n",
       "\n",
       "    this.ws.onopen =  function () {\n",
       "            fig.send_message(\"supports_binary\", {value: fig.supports_binary});\n",
       "            fig.send_message(\"send_image_mode\", {});\n",
       "            if (mpl.ratio != 1) {\n",
       "                fig.send_message(\"set_dpi_ratio\", {'dpi_ratio': mpl.ratio});\n",
       "            }\n",
       "            fig.send_message(\"refresh\", {});\n",
       "        }\n",
       "\n",
       "    this.imageObj.onload = function() {\n",
       "            if (fig.image_mode == 'full') {\n",
       "                // Full images could contain transparency (where diff images\n",
       "                // almost always do), so we need to clear the canvas so that\n",
       "                // there is no ghosting.\n",
       "                fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n",
       "            }\n",
       "            fig.context.drawImage(fig.imageObj, 0, 0);\n",
       "        };\n",
       "\n",
       "    this.imageObj.onunload = function() {\n",
       "        fig.ws.close();\n",
       "    }\n",
       "\n",
       "    this.ws.onmessage = this._make_on_message_function(this);\n",
       "\n",
       "    this.ondownload = ondownload;\n",
       "}\n",
       "\n",
       "mpl.figure.prototype._init_header = function() {\n",
       "    var titlebar = $(\n",
       "        '<div class=\"ui-dialog-titlebar ui-widget-header ui-corner-all ' +\n",
       "        'ui-helper-clearfix\"/>');\n",
       "    var titletext = $(\n",
       "        '<div class=\"ui-dialog-title\" style=\"width: 100%; ' +\n",
       "        'text-align: center; padding: 3px;\"/>');\n",
       "    titlebar.append(titletext)\n",
       "    this.root.append(titlebar);\n",
       "    this.header = titletext[0];\n",
       "}\n",
       "\n",
       "\n",
       "\n",
       "mpl.figure.prototype._canvas_extra_style = function(canvas_div) {\n",
       "\n",
       "}\n",
       "\n",
       "\n",
       "mpl.figure.prototype._root_extra_style = function(canvas_div) {\n",
       "\n",
       "}\n",
       "\n",
       "mpl.figure.prototype._init_canvas = function() {\n",
       "    var fig = this;\n",
       "\n",
       "    var canvas_div = $('<div/>');\n",
       "\n",
       "    canvas_div.attr('style', 'position: relative; clear: both; outline: 0');\n",
       "\n",
       "    function canvas_keyboard_event(event) {\n",
       "        return fig.key_event(event, event['data']);\n",
       "    }\n",
       "\n",
       "    canvas_div.keydown('key_press', canvas_keyboard_event);\n",
       "    canvas_div.keyup('key_release', canvas_keyboard_event);\n",
       "    this.canvas_div = canvas_div\n",
       "    this._canvas_extra_style(canvas_div)\n",
       "    this.root.append(canvas_div);\n",
       "\n",
       "    var canvas = $('<canvas/>');\n",
       "    canvas.addClass('mpl-canvas');\n",
       "    canvas.attr('style', \"left: 0; top: 0; z-index: 0; outline: 0\")\n",
       "\n",
       "    this.canvas = canvas[0];\n",
       "    this.context = canvas[0].getContext(\"2d\");\n",
       "\n",
       "    var backingStore = this.context.backingStorePixelRatio ||\n",
       "\tthis.context.webkitBackingStorePixelRatio ||\n",
       "\tthis.context.mozBackingStorePixelRatio ||\n",
       "\tthis.context.msBackingStorePixelRatio ||\n",
       "\tthis.context.oBackingStorePixelRatio ||\n",
       "\tthis.context.backingStorePixelRatio || 1;\n",
       "\n",
       "    mpl.ratio = (window.devicePixelRatio || 1) / backingStore;\n",
       "\n",
       "    var rubberband = $('<canvas/>');\n",
       "    rubberband.attr('style', \"position: absolute; left: 0; top: 0; z-index: 1;\")\n",
       "\n",
       "    var pass_mouse_events = true;\n",
       "\n",
       "    canvas_div.resizable({\n",
       "        start: function(event, ui) {\n",
       "            pass_mouse_events = false;\n",
       "        },\n",
       "        resize: function(event, ui) {\n",
       "            fig.request_resize(ui.size.width, ui.size.height);\n",
       "        },\n",
       "        stop: function(event, ui) {\n",
       "            pass_mouse_events = true;\n",
       "            fig.request_resize(ui.size.width, ui.size.height);\n",
       "        },\n",
       "    });\n",
       "\n",
       "    function mouse_event_fn(event) {\n",
       "        if (pass_mouse_events)\n",
       "            return fig.mouse_event(event, event['data']);\n",
       "    }\n",
       "\n",
       "    rubberband.mousedown('button_press', mouse_event_fn);\n",
       "    rubberband.mouseup('button_release', mouse_event_fn);\n",
       "    // Throttle sequential mouse events to 1 every 20ms.\n",
       "    rubberband.mousemove('motion_notify', mouse_event_fn);\n",
       "\n",
       "    rubberband.mouseenter('figure_enter', mouse_event_fn);\n",
       "    rubberband.mouseleave('figure_leave', mouse_event_fn);\n",
       "\n",
       "    canvas_div.on(\"wheel\", function (event) {\n",
       "        event = event.originalEvent;\n",
       "        event['data'] = 'scroll'\n",
       "        if (event.deltaY < 0) {\n",
       "            event.step = 1;\n",
       "        } else {\n",
       "            event.step = -1;\n",
       "        }\n",
       "        mouse_event_fn(event);\n",
       "    });\n",
       "\n",
       "    canvas_div.append(canvas);\n",
       "    canvas_div.append(rubberband);\n",
       "\n",
       "    this.rubberband = rubberband;\n",
       "    this.rubberband_canvas = rubberband[0];\n",
       "    this.rubberband_context = rubberband[0].getContext(\"2d\");\n",
       "    this.rubberband_context.strokeStyle = \"#000000\";\n",
       "\n",
       "    this._resize_canvas = function(width, height) {\n",
       "        // Keep the size of the canvas, canvas container, and rubber band\n",
       "        // canvas in synch.\n",
       "        canvas_div.css('width', width)\n",
       "        canvas_div.css('height', height)\n",
       "\n",
       "        canvas.attr('width', width * mpl.ratio);\n",
       "        canvas.attr('height', height * mpl.ratio);\n",
       "        canvas.attr('style', 'width: ' + width + 'px; height: ' + height + 'px;');\n",
       "\n",
       "        rubberband.attr('width', width);\n",
       "        rubberband.attr('height', height);\n",
       "    }\n",
       "\n",
       "    // Set the figure to an initial 600x600px, this will subsequently be updated\n",
       "    // upon first draw.\n",
       "    this._resize_canvas(600, 600);\n",
       "\n",
       "    // Disable right mouse context menu.\n",
       "    $(this.rubberband_canvas).bind(\"contextmenu\",function(e){\n",
       "        return false;\n",
       "    });\n",
       "\n",
       "    function set_focus () {\n",
       "        canvas.focus();\n",
       "        canvas_div.focus();\n",
       "    }\n",
       "\n",
       "    window.setTimeout(set_focus, 100);\n",
       "}\n",
       "\n",
       "mpl.figure.prototype._init_toolbar = function() {\n",
       "    var fig = this;\n",
       "\n",
       "    var nav_element = $('<div/>');\n",
       "    nav_element.attr('style', 'width: 100%');\n",
       "    this.root.append(nav_element);\n",
       "\n",
       "    // Define a callback function for later on.\n",
       "    function toolbar_event(event) {\n",
       "        return fig.toolbar_button_onclick(event['data']);\n",
       "    }\n",
       "    function toolbar_mouse_event(event) {\n",
       "        return fig.toolbar_button_onmouseover(event['data']);\n",
       "    }\n",
       "\n",
       "    for(var toolbar_ind in mpl.toolbar_items) {\n",
       "        var name = mpl.toolbar_items[toolbar_ind][0];\n",
       "        var tooltip = mpl.toolbar_items[toolbar_ind][1];\n",
       "        var image = mpl.toolbar_items[toolbar_ind][2];\n",
       "        var method_name = mpl.toolbar_items[toolbar_ind][3];\n",
       "\n",
       "        if (!name) {\n",
       "            // put a spacer in here.\n",
       "            continue;\n",
       "        }\n",
       "        var button = $('<button/>');\n",
       "        button.addClass('ui-button ui-widget ui-state-default ui-corner-all ' +\n",
       "                        'ui-button-icon-only');\n",
       "        button.attr('role', 'button');\n",
       "        button.attr('aria-disabled', 'false');\n",
       "        button.click(method_name, toolbar_event);\n",
       "        button.mouseover(tooltip, toolbar_mouse_event);\n",
       "\n",
       "        var icon_img = $('<span/>');\n",
       "        icon_img.addClass('ui-button-icon-primary ui-icon');\n",
       "        icon_img.addClass(image);\n",
       "        icon_img.addClass('ui-corner-all');\n",
       "\n",
       "        var tooltip_span = $('<span/>');\n",
       "        tooltip_span.addClass('ui-button-text');\n",
       "        tooltip_span.html(tooltip);\n",
       "\n",
       "        button.append(icon_img);\n",
       "        button.append(tooltip_span);\n",
       "\n",
       "        nav_element.append(button);\n",
       "    }\n",
       "\n",
       "    var fmt_picker_span = $('<span/>');\n",
       "\n",
       "    var fmt_picker = $('<select/>');\n",
       "    fmt_picker.addClass('mpl-toolbar-option ui-widget ui-widget-content');\n",
       "    fmt_picker_span.append(fmt_picker);\n",
       "    nav_element.append(fmt_picker_span);\n",
       "    this.format_dropdown = fmt_picker[0];\n",
       "\n",
       "    for (var ind in mpl.extensions) {\n",
       "        var fmt = mpl.extensions[ind];\n",
       "        var option = $(\n",
       "            '<option/>', {selected: fmt === mpl.default_extension}).html(fmt);\n",
       "        fmt_picker.append(option);\n",
       "    }\n",
       "\n",
       "    // Add hover states to the ui-buttons\n",
       "    $( \".ui-button\" ).hover(\n",
       "        function() { $(this).addClass(\"ui-state-hover\");},\n",
       "        function() { $(this).removeClass(\"ui-state-hover\");}\n",
       "    );\n",
       "\n",
       "    var status_bar = $('<span class=\"mpl-message\"/>');\n",
       "    nav_element.append(status_bar);\n",
       "    this.message = status_bar[0];\n",
       "}\n",
       "\n",
       "mpl.figure.prototype.request_resize = function(x_pixels, y_pixels) {\n",
       "    // Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client,\n",
       "    // which will in turn request a refresh of the image.\n",
       "    this.send_message('resize', {'width': x_pixels, 'height': y_pixels});\n",
       "}\n",
       "\n",
       "mpl.figure.prototype.send_message = function(type, properties) {\n",
       "    properties['type'] = type;\n",
       "    properties['figure_id'] = this.id;\n",
       "    this.ws.send(JSON.stringify(properties));\n",
       "}\n",
       "\n",
       "mpl.figure.prototype.send_draw_message = function() {\n",
       "    if (!this.waiting) {\n",
       "        this.waiting = true;\n",
       "        this.ws.send(JSON.stringify({type: \"draw\", figure_id: this.id}));\n",
       "    }\n",
       "}\n",
       "\n",
       "\n",
       "mpl.figure.prototype.handle_save = function(fig, msg) {\n",
       "    var format_dropdown = fig.format_dropdown;\n",
       "    var format = format_dropdown.options[format_dropdown.selectedIndex].value;\n",
       "    fig.ondownload(fig, format);\n",
       "}\n",
       "\n",
       "\n",
       "mpl.figure.prototype.handle_resize = function(fig, msg) {\n",
       "    var size = msg['size'];\n",
       "    if (size[0] != fig.canvas.width || size[1] != fig.canvas.height) {\n",
       "        fig._resize_canvas(size[0], size[1]);\n",
       "        fig.send_message(\"refresh\", {});\n",
       "    };\n",
       "}\n",
       "\n",
       "mpl.figure.prototype.handle_rubberband = function(fig, msg) {\n",
       "    var x0 = msg['x0'] / mpl.ratio;\n",
       "    var y0 = (fig.canvas.height - msg['y0']) / mpl.ratio;\n",
       "    var x1 = msg['x1'] / mpl.ratio;\n",
       "    var y1 = (fig.canvas.height - msg['y1']) / mpl.ratio;\n",
       "    x0 = Math.floor(x0) + 0.5;\n",
       "    y0 = Math.floor(y0) + 0.5;\n",
       "    x1 = Math.floor(x1) + 0.5;\n",
       "    y1 = Math.floor(y1) + 0.5;\n",
       "    var min_x = Math.min(x0, x1);\n",
       "    var min_y = Math.min(y0, y1);\n",
       "    var width = Math.abs(x1 - x0);\n",
       "    var height = Math.abs(y1 - y0);\n",
       "\n",
       "    fig.rubberband_context.clearRect(\n",
       "        0, 0, fig.canvas.width / mpl.ratio, fig.canvas.height / mpl.ratio);\n",
       "\n",
       "    fig.rubberband_context.strokeRect(min_x, min_y, width, height);\n",
       "}\n",
       "\n",
       "mpl.figure.prototype.handle_figure_label = function(fig, msg) {\n",
       "    // Updates the figure title.\n",
       "    fig.header.textContent = msg['label'];\n",
       "}\n",
       "\n",
       "mpl.figure.prototype.handle_cursor = function(fig, msg) {\n",
       "    var cursor = msg['cursor'];\n",
       "    switch(cursor)\n",
       "    {\n",
       "    case 0:\n",
       "        cursor = 'pointer';\n",
       "        break;\n",
       "    case 1:\n",
       "        cursor = 'default';\n",
       "        break;\n",
       "    case 2:\n",
       "        cursor = 'crosshair';\n",
       "        break;\n",
       "    case 3:\n",
       "        cursor = 'move';\n",
       "        break;\n",
       "    }\n",
       "    fig.rubberband_canvas.style.cursor = cursor;\n",
       "}\n",
       "\n",
       "mpl.figure.prototype.handle_message = function(fig, msg) {\n",
       "    fig.message.textContent = msg['message'];\n",
       "}\n",
       "\n",
       "mpl.figure.prototype.handle_draw = function(fig, msg) {\n",
       "    // Request the server to send over a new figure.\n",
       "    fig.send_draw_message();\n",
       "}\n",
       "\n",
       "mpl.figure.prototype.handle_image_mode = function(fig, msg) {\n",
       "    fig.image_mode = msg['mode'];\n",
       "}\n",
       "\n",
       "mpl.figure.prototype.updated_canvas_event = function() {\n",
       "    // Called whenever the canvas gets updated.\n",
       "    this.send_message(\"ack\", {});\n",
       "}\n",
       "\n",
       "// A function to construct a web socket function for onmessage handling.\n",
       "// Called in the figure constructor.\n",
       "mpl.figure.prototype._make_on_message_function = function(fig) {\n",
       "    return function socket_on_message(evt) {\n",
       "        if (evt.data instanceof Blob) {\n",
       "            /* FIXME: We get \"Resource interpreted as Image but\n",
       "             * transferred with MIME type text/plain:\" errors on\n",
       "             * Chrome.  But how to set the MIME type?  It doesn't seem\n",
       "             * to be part of the websocket stream */\n",
       "            evt.data.type = \"image/png\";\n",
       "\n",
       "            /* Free the memory for the previous frames */\n",
       "            if (fig.imageObj.src) {\n",
       "                (window.URL || window.webkitURL).revokeObjectURL(\n",
       "                    fig.imageObj.src);\n",
       "            }\n",
       "\n",
       "            fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL(\n",
       "                evt.data);\n",
       "            fig.updated_canvas_event();\n",
       "            fig.waiting = false;\n",
       "            return;\n",
       "        }\n",
       "        else if (typeof evt.data === 'string' && evt.data.slice(0, 21) == \"data:image/png;base64\") {\n",
       "            fig.imageObj.src = evt.data;\n",
       "            fig.updated_canvas_event();\n",
       "            fig.waiting = false;\n",
       "            return;\n",
       "        }\n",
       "\n",
       "        var msg = JSON.parse(evt.data);\n",
       "        var msg_type = msg['type'];\n",
       "\n",
       "        // Call the  \"handle_{type}\" callback, which takes\n",
       "        // the figure and JSON message as its only arguments.\n",
       "        try {\n",
       "            var callback = fig[\"handle_\" + msg_type];\n",
       "        } catch (e) {\n",
       "            console.log(\"No handler for the '\" + msg_type + \"' message type: \", msg);\n",
       "            return;\n",
       "        }\n",
       "\n",
       "        if (callback) {\n",
       "            try {\n",
       "                // console.log(\"Handling '\" + msg_type + \"' message: \", msg);\n",
       "                callback(fig, msg);\n",
       "            } catch (e) {\n",
       "                console.log(\"Exception inside the 'handler_\" + msg_type + \"' callback:\", e, e.stack, msg);\n",
       "            }\n",
       "        }\n",
       "    };\n",
       "}\n",
       "\n",
       "// from http://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas\n",
       "mpl.findpos = function(e) {\n",
       "    //this section is from http://www.quirksmode.org/js/events_properties.html\n",
       "    var targ;\n",
       "    if (!e)\n",
       "        e = window.event;\n",
       "    if (e.target)\n",
       "        targ = e.target;\n",
       "    else if (e.srcElement)\n",
       "        targ = e.srcElement;\n",
       "    if (targ.nodeType == 3) // defeat Safari bug\n",
       "        targ = targ.parentNode;\n",
       "\n",
       "    // jQuery normalizes the pageX and pageY\n",
       "    // pageX,Y are the mouse positions relative to the document\n",
       "    // offset() returns the position of the element relative to the document\n",
       "    var x = e.pageX - $(targ).offset().left;\n",
       "    var y = e.pageY - $(targ).offset().top;\n",
       "\n",
       "    return {\"x\": x, \"y\": y};\n",
       "};\n",
       "\n",
       "/*\n",
       " * return a copy of an object with only non-object keys\n",
       " * we need this to avoid circular references\n",
       " * http://stackoverflow.com/a/24161582/3208463\n",
       " */\n",
       "function simpleKeys (original) {\n",
       "  return Object.keys(original).reduce(function (obj, key) {\n",
       "    if (typeof original[key] !== 'object')\n",
       "        obj[key] = original[key]\n",
       "    return obj;\n",
       "  }, {});\n",
       "}\n",
       "\n",
       "mpl.figure.prototype.mouse_event = function(event, name) {\n",
       "    var canvas_pos = mpl.findpos(event)\n",
       "\n",
       "    if (name === 'button_press')\n",
       "    {\n",
       "        this.canvas.focus();\n",
       "        this.canvas_div.focus();\n",
       "    }\n",
       "\n",
       "    var x = canvas_pos.x * mpl.ratio;\n",
       "    var y = canvas_pos.y * mpl.ratio;\n",
       "\n",
       "    this.send_message(name, {x: x, y: y, button: event.button,\n",
       "                             step: event.step,\n",
       "                             guiEvent: simpleKeys(event)});\n",
       "\n",
       "    /* This prevents the web browser from automatically changing to\n",
       "     * the text insertion cursor when the button is pressed.  We want\n",
       "     * to control all of the cursor setting manually through the\n",
       "     * 'cursor' event from matplotlib */\n",
       "    event.preventDefault();\n",
       "    return false;\n",
       "}\n",
       "\n",
       "mpl.figure.prototype._key_event_extra = function(event, name) {\n",
       "    // Handle any extra behaviour associated with a key event\n",
       "}\n",
       "\n",
       "mpl.figure.prototype.key_event = function(event, name) {\n",
       "\n",
       "    // Prevent repeat events\n",
       "    if (name == 'key_press')\n",
       "    {\n",
       "        if (event.which === this._key)\n",
       "            return;\n",
       "        else\n",
       "            this._key = event.which;\n",
       "    }\n",
       "    if (name == 'key_release')\n",
       "        this._key = null;\n",
       "\n",
       "    var value = '';\n",
       "    if (event.ctrlKey && event.which != 17)\n",
       "        value += \"ctrl+\";\n",
       "    if (event.altKey && event.which != 18)\n",
       "        value += \"alt+\";\n",
       "    if (event.shiftKey && event.which != 16)\n",
       "        value += \"shift+\";\n",
       "\n",
       "    value += 'k';\n",
       "    value += event.which.toString();\n",
       "\n",
       "    this._key_event_extra(event, name);\n",
       "\n",
       "    this.send_message(name, {key: value,\n",
       "                             guiEvent: simpleKeys(event)});\n",
       "    return false;\n",
       "}\n",
       "\n",
       "mpl.figure.prototype.toolbar_button_onclick = function(name) {\n",
       "    if (name == 'download') {\n",
       "        this.handle_save(this, null);\n",
       "    } else {\n",
       "        this.send_message(\"toolbar_button\", {name: name});\n",
       "    }\n",
       "};\n",
       "\n",
       "mpl.figure.prototype.toolbar_button_onmouseover = function(tooltip) {\n",
       "    this.message.textContent = tooltip;\n",
       "};\n",
       "mpl.toolbar_items = [[\"Home\", \"Reset original view\", \"fa fa-home icon-home\", \"home\"], [\"Back\", \"Back to previous view\", \"fa fa-arrow-left icon-arrow-left\", \"back\"], [\"Forward\", \"Forward to next view\", \"fa fa-arrow-right icon-arrow-right\", \"forward\"], [\"\", \"\", \"\", \"\"], [\"Pan\", \"Pan axes with left mouse, zoom with right\", \"fa fa-arrows icon-move\", \"pan\"], [\"Zoom\", \"Zoom to rectangle\", \"fa fa-square-o icon-check-empty\", \"zoom\"], [\"\", \"\", \"\", \"\"], [\"Download\", \"Download plot\", \"fa fa-floppy-o icon-save\", \"download\"]];\n",
       "\n",
       "mpl.extensions = [\"eps\", \"jpeg\", \"pdf\", \"png\", \"ps\", \"raw\", \"svg\", \"tif\"];\n",
       "\n",
       "mpl.default_extension = \"png\";var comm_websocket_adapter = function(comm) {\n",
       "    // Create a \"websocket\"-like object which calls the given IPython comm\n",
       "    // object with the appropriate methods. Currently this is a non binary\n",
       "    // socket, so there is still some room for performance tuning.\n",
       "    var ws = {};\n",
       "\n",
       "    ws.close = function() {\n",
       "        comm.close()\n",
       "    };\n",
       "    ws.send = function(m) {\n",
       "        //console.log('sending', m);\n",
       "        comm.send(m);\n",
       "    };\n",
       "    // Register the callback with on_msg.\n",
       "    comm.on_msg(function(msg) {\n",
       "        //console.log('receiving', msg['content']['data'], msg);\n",
       "        // Pass the mpl event to the overridden (by mpl) onmessage function.\n",
       "        ws.onmessage(msg['content']['data'])\n",
       "    });\n",
       "    return ws;\n",
       "}\n",
       "\n",
       "mpl.mpl_figure_comm = function(comm, msg) {\n",
       "    // This is the function which gets called when the mpl process\n",
       "    // starts-up an IPython Comm through the \"matplotlib\" channel.\n",
       "\n",
       "    var id = msg.content.data.id;\n",
       "    // Get hold of the div created by the display call when the Comm\n",
       "    // socket was opened in Python.\n",
       "    var element = $(\"#\" + id);\n",
       "    var ws_proxy = comm_websocket_adapter(comm)\n",
       "\n",
       "    function ondownload(figure, format) {\n",
       "        window.open(figure.imageObj.src);\n",
       "    }\n",
       "\n",
       "    var fig = new mpl.figure(id, ws_proxy,\n",
       "                           ondownload,\n",
       "                           element.get(0));\n",
       "\n",
       "    // Call onopen now - mpl needs it, as it is assuming we've passed it a real\n",
       "    // web socket which is closed, not our websocket->open comm proxy.\n",
       "    ws_proxy.onopen();\n",
       "\n",
       "    fig.parent_element = element.get(0);\n",
       "    fig.cell_info = mpl.find_output_cell(\"<div id='\" + id + \"'></div>\");\n",
       "    if (!fig.cell_info) {\n",
       "        console.error(\"Failed to find cell for figure\", id, fig);\n",
       "        return;\n",
       "    }\n",
       "\n",
       "    var output_index = fig.cell_info[2]\n",
       "    var cell = fig.cell_info[0];\n",
       "\n",
       "};\n",
       "\n",
       "mpl.figure.prototype.handle_close = function(fig, msg) {\n",
       "    var width = fig.canvas.width/mpl.ratio\n",
       "    fig.root.unbind('remove')\n",
       "\n",
       "    // Update the output cell to use the data from the current canvas.\n",
       "    fig.push_to_output();\n",
       "    var dataURL = fig.canvas.toDataURL();\n",
       "    // Re-enable the keyboard manager in IPython - without this line, in FF,\n",
       "    // the notebook keyboard shortcuts fail.\n",
       "    IPython.keyboard_manager.enable()\n",
       "    $(fig.parent_element).html('<img src=\"' + dataURL + '\" width=\"' + width + '\">');\n",
       "    fig.close_ws(fig, msg);\n",
       "}\n",
       "\n",
       "mpl.figure.prototype.close_ws = function(fig, msg){\n",
       "    fig.send_message('closing', msg);\n",
       "    // fig.ws.close()\n",
       "}\n",
       "\n",
       "mpl.figure.prototype.push_to_output = function(remove_interactive) {\n",
       "    // Turn the data on the canvas into data in the output cell.\n",
       "    var width = this.canvas.width/mpl.ratio\n",
       "    var dataURL = this.canvas.toDataURL();\n",
       "    this.cell_info[1]['text/html'] = '<img src=\"' + dataURL + '\" width=\"' + width + '\">';\n",
       "}\n",
       "\n",
       "mpl.figure.prototype.updated_canvas_event = function() {\n",
       "    // Tell IPython that the notebook contents must change.\n",
       "    IPython.notebook.set_dirty(true);\n",
       "    this.send_message(\"ack\", {});\n",
       "    var fig = this;\n",
       "    // Wait a second, then push the new image to the DOM so\n",
       "    // that it is saved nicely (might be nice to debounce this).\n",
       "    setTimeout(function () { fig.push_to_output() }, 1000);\n",
       "}\n",
       "\n",
       "mpl.figure.prototype._init_toolbar = function() {\n",
       "    var fig = this;\n",
       "\n",
       "    var nav_element = $('<div/>');\n",
       "    nav_element.attr('style', 'width: 100%');\n",
       "    this.root.append(nav_element);\n",
       "\n",
       "    // Define a callback function for later on.\n",
       "    function toolbar_event(event) {\n",
       "        return fig.toolbar_button_onclick(event['data']);\n",
       "    }\n",
       "    function toolbar_mouse_event(event) {\n",
       "        return fig.toolbar_button_onmouseover(event['data']);\n",
       "    }\n",
       "\n",
       "    for(var toolbar_ind in mpl.toolbar_items){\n",
       "        var name = mpl.toolbar_items[toolbar_ind][0];\n",
       "        var tooltip = mpl.toolbar_items[toolbar_ind][1];\n",
       "        var image = mpl.toolbar_items[toolbar_ind][2];\n",
       "        var method_name = mpl.toolbar_items[toolbar_ind][3];\n",
       "\n",
       "        if (!name) { continue; };\n",
       "\n",
       "        var button = $('<button class=\"btn btn-default\" href=\"#\" title=\"' + name + '\"><i class=\"fa ' + image + ' fa-lg\"></i></button>');\n",
       "        button.click(method_name, toolbar_event);\n",
       "        button.mouseover(tooltip, toolbar_mouse_event);\n",
       "        nav_element.append(button);\n",
       "    }\n",
       "\n",
       "    // Add the status bar.\n",
       "    var status_bar = $('<span class=\"mpl-message\" style=\"text-align:right; float: right;\"/>');\n",
       "    nav_element.append(status_bar);\n",
       "    this.message = status_bar[0];\n",
       "\n",
       "    // Add the close button to the window.\n",
       "    var buttongrp = $('<div class=\"btn-group inline pull-right\"></div>');\n",
       "    var button = $('<button class=\"btn btn-mini btn-primary\" href=\"#\" title=\"Stop Interaction\"><i class=\"fa fa-power-off icon-remove icon-large\"></i></button>');\n",
       "    button.click(function (evt) { fig.handle_close(fig, {}); } );\n",
       "    button.mouseover('Stop Interaction', toolbar_mouse_event);\n",
       "    buttongrp.append(button);\n",
       "    var titlebar = this.root.find($('.ui-dialog-titlebar'));\n",
       "    titlebar.prepend(buttongrp);\n",
       "}\n",
       "\n",
       "mpl.figure.prototype._root_extra_style = function(el){\n",
       "    var fig = this\n",
       "    el.on(\"remove\", function(){\n",
       "\tfig.close_ws(fig, {});\n",
       "    });\n",
       "}\n",
       "\n",
       "mpl.figure.prototype._canvas_extra_style = function(el){\n",
       "    // this is important to make the div 'focusable\n",
       "    el.attr('tabindex', 0)\n",
       "    // reach out to IPython and tell the keyboard manager to turn it's self\n",
       "    // off when our div gets focus\n",
       "\n",
       "    // location in version 3\n",
       "    if (IPython.notebook.keyboard_manager) {\n",
       "        IPython.notebook.keyboard_manager.register_events(el);\n",
       "    }\n",
       "    else {\n",
       "        // location in version 2\n",
       "        IPython.keyboard_manager.register_events(el);\n",
       "    }\n",
       "\n",
       "}\n",
       "\n",
       "mpl.figure.prototype._key_event_extra = function(event, name) {\n",
       "    var manager = IPython.notebook.keyboard_manager;\n",
       "    if (!manager)\n",
       "        manager = IPython.keyboard_manager;\n",
       "\n",
       "    // Check for shift+enter\n",
       "    if (event.shiftKey && event.which == 13) {\n",
       "        this.canvas_div.blur();\n",
       "        // select the cell after this one\n",
       "        var index = IPython.notebook.find_cell_index(this.cell_info[0]);\n",
       "        IPython.notebook.select(index + 1);\n",
       "    }\n",
       "}\n",
       "\n",
       "mpl.figure.prototype.handle_save = function(fig, msg) {\n",
       "    fig.ondownload(fig, null);\n",
       "}\n",
       "\n",
       "\n",
       "mpl.find_output_cell = function(html_output) {\n",
       "    // Return the cell and output element which can be found *uniquely* in the notebook.\n",
       "    // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n",
       "    // IPython event is triggered only after the cells have been serialised, which for\n",
       "    // our purposes (turning an active figure into a static one), is too late.\n",
       "    var cells = IPython.notebook.get_cells();\n",
       "    var ncells = cells.length;\n",
       "    for (var i=0; i<ncells; i++) {\n",
       "        var cell = cells[i];\n",
       "        if (cell.cell_type === 'code'){\n",
       "            for (var j=0; j<cell.output_area.outputs.length; j++) {\n",
       "                var data = cell.output_area.outputs[j];\n",
       "                if (data.data) {\n",
       "                    // IPython >= 3 moved mimebundle to data attribute of output\n",
       "                    data = data.data;\n",
       "                }\n",
       "                if (data['text/html'] == html_output) {\n",
       "                    return [cell, data, j];\n",
       "                }\n",
       "            }\n",
       "        }\n",
       "    }\n",
       "}\n",
       "\n",
       "// Register the function which deals with the matplotlib target/channel.\n",
       "// The kernel may be null if the page has been refreshed.\n",
       "if (IPython.notebook.kernel != null) {\n",
       "    IPython.notebook.kernel.comm_manager.register_target('matplotlib', mpl.mpl_figure_comm);\n",
       "}\n"
      ],
      "text/plain": [
       "<IPython.core.display.Javascript object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "<img src=\"\" width=\"796\">"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "\n",
    "class TestStrategy(bt.Strategy):\n",
    "    \"\"\"\n",
    "    构建自己的策略\n",
    "    \"\"\"\n",
    "\n",
    "    def log(self, txt, dt=None, doprint=False):\n",
    "        ''' 日志函数，用于统一输出日志格式 '''\n",
    "        if doprint:\n",
    "            dt = dt or self.datas[0].datetime.date(0)\n",
    "            print('%s, %s' % (dt.isoformat(), txt))\n",
    "\n",
    "    def __init__(self):\n",
    "\n",
    "        # 初始化相关数据\n",
    "        self.dataclose = self.datas[0].close\n",
    "        # 成交量\n",
    "        self.volume = self.datas[0].volume\n",
    "        self.order = None\n",
    "        self.buyprice = None\n",
    "        self.buycomm = None\n",
    "\n",
    "        # 计算两个EMA均线和MACD信号\n",
    "        ema1 = EMA(self.data, period=18)\n",
    "        ema2 = EMA(self.data, period=47)\n",
    "        self.macd = ema1 - ema2\n",
    "        self.signal = EMA(self.macd, period=9)\n",
    "        #画图\n",
    "        bt.indicators.MACDHisto(self.data)\n",
    "\n",
    "        # 9个交易日内最高价\n",
    "        self.high_nine = bt.indicators.Highest(self.data.high, period=9)\n",
    "        # 9个交易日内最低价\n",
    "        self.low_nine = bt.indicators.Lowest(self.data.low, period=9)\n",
    "        # 计算rsv值\n",
    "        self.rsv = 100 * bt.DivByZero(\n",
    "            self.data_close - self.low_nine, self.high_nine - self.low_nine, zero=None\n",
    "        )\n",
    "        # 计算rsv的3周期加权平均值，即K值\n",
    "        self.K = bt.indicators.EMA(self.rsv, period=3)\n",
    "        # D值=K值的3周期加权平均值\n",
    "        self.D = bt.indicators.EMA(self.K, period=3)\n",
    "        # J=3*K-2*D\n",
    "        self.J = 3 * self.K - 2 * self.D\n",
    "\n",
    "\n",
    "\n",
    "    def notify_order(self, order):\n",
    "        \"\"\"\n",
    "        订单状态处理\n",
    "        Arguments:\n",
    "            order {object} -- 订单状态\n",
    "        \"\"\"\n",
    "        if order.status in [order.Submitted, order.Accepted]:\n",
    "            # 如订单已被处理，则不用做任何事情\n",
    "            return\n",
    "\n",
    "        # 检查订单是否完成\n",
    "        if order.status in [order.Completed]:\n",
    "            if order.isbuy():\n",
    "                self.buyprice = order.executed.price\n",
    "                self.buycomm = order.executed.comm\n",
    "            self.bar_executed = len(self)\n",
    "\n",
    "        # 订单因为缺少资金之类的原因被拒绝执行\n",
    "        elif order.status in [order.Canceled, order.Margin, order.Rejected]:\n",
    "            self.log('订单取消或被拒绝',doprint=True)\n",
    "\n",
    "        # 订单状态处理完成，设为空\n",
    "        self.order = None\n",
    "\n",
    "    def notify_trade(self, trade):\n",
    "        \"\"\"\n",
    "        交易成果\n",
    "        \n",
    "        Arguments:\n",
    "            trade {object} -- 交易状态\n",
    "        \"\"\"\n",
    "        if not trade.isclosed:\n",
    "            return\n",
    "\n",
    "        # 显示交易的毛利率和净利润\n",
    "        self.log('交易中，毛利%.2f, 净利 %.2f' %\n",
    "                 (trade.pnl, trade.pnlcomm), doprint=True)\n",
    "\n",
    "    def next(self):\n",
    "        ''' 下一次执行 '''\n",
    "\n",
    "        # 记录收盘价\n",
    "        self.log('Close, %.2f' % self.dataclose[0])\n",
    "\n",
    "        # 是否正在下单，如果是的话不能提交第二次订单\n",
    "        if self.order:\n",
    "            return\n",
    "\n",
    "        # 是否已经买入\n",
    "\n",
    "        if not self.position:\n",
    "            #第一个条件，前一天di\n",
    "            condition1 = self.J[-1] - self.D[-1]\n",
    "            condition2 = self.J[0] - self.D[0]\n",
    "            if condition1 < 0 and condition2 > 0:\n",
    "                self.log('买入, %.2f' % self.dataclose[0],doprint=True)\n",
    "                self.order = self.buy()\n",
    "        else:\n",
    "            condition1 = self.macd[-1] - self.signal[-1]\n",
    "            condition2 = self.macd[0] - self.signal[0]\n",
    "            if condition1 > 0 and condition2 < 0:\n",
    "                self.log('卖出, %.2f' % self.dataclose[0],doprint=True)\n",
    "                self.order = self.sell()\n",
    "\n",
    "    def stop(self):\n",
    "        self.log(u'最终的账户资产为%.2f' %\n",
    "                 (self.broker.getvalue()), doprint=True)\n",
    "\n",
    "\n",
    "if __name__ == '__main__':\n",
    "\n",
    "    # 初始化模型\n",
    "    cerebro = bt.Cerebro()\n",
    "\n",
    "    # 构建策略\n",
    "    strats = cerebro.addstrategy(TestStrategy)\n",
    "    # 每次买100股\n",
    "    cerebro.addsizer(bt.sizers.FixedSize, stake=100)\n",
    "\n",
    "    # 加载数据到模型中\n",
    "    data = bt.feeds.GenericCSVData(\n",
    "        dataname='../第一课/history_A_stock_k_data.csv',\n",
    "        fromdate=datetime.datetime(2020, 1, 1),\n",
    "        todate=datetime.datetime(2023, 2, 12),\n",
    "        dtformat='%Y-%m-%d',\n",
    "        datetime=0,\n",
    "        open=2,\n",
    "        high=3,\n",
    "        low=4,\n",
    "        close=5,\n",
    "        volume=7\n",
    "    )\n",
    "    cerebro.adddata(data)\n",
    "\n",
    "    # 设定初始资金和佣金\n",
    "    cerebro.broker.setcash(2000000.0)\n",
    "    cerebro.broker.setcommission(0.005)\n",
    "\n",
    "    # 策略执行前的资金\n",
    "    print('启动资金: %.2f' % cerebro.broker.getvalue())\n",
    "\n",
    "    # 策略执行\n",
    "    cerebro.run()\n",
    "    # 画图\n",
    "    cerebro.plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "91a9bd5f",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
